import { Component, Graphics, Layers, Node, UITransform, _decorator } from 'cc';
import Sinusoid from '../Math/Sinusoid';

const { ccclass, property } = _decorator;

@ccclass('WaveManager')
export class WaveManager extends Component {
    @property({ type: Node })
    pen: Node = null;


    start() {
        this.pen.layer = Layers.Enum.UI_2D;
        let ctx = this.pen.getComponent(Graphics);
        ctx.lineWidth = 3;
        ctx.strokeColor.fromHEX('#44A5FF');
        ctx.fillColor.fromHEX('#44A5FF');
    }


    draw(sinusoid: Sinusoid) {
        let ctx = this.pen.getComponent(Graphics);
        ctx.clear();
        let { width, height } = this.node.getComponent(UITransform);

        let waveW = width;
        let waveH = height / 2 - sinusoid.A;
        let waveX = -width / 2;
        let waveY = -height / 2;
        ctx.rect(waveX, waveY, waveW, waveH);



        let pW = this.pen.parent.getComponent(UITransform).width;

        let startX = -pW / 2;
        let endX = pW / 2;


        // 得到矩形y坐标
        let rectTopY = waveY + waveH;
        // 矩形y坐标往上波的振幅高度，就是波的偏移量
        sinusoid.d = rectTopY + sinusoid.A;

        ctx.moveTo(startX, rectTopY);

        for (let i = startX; i < endX; i++) {
            ctx.lineTo(i, sinusoid.getY(i))
        }
        // 最后移动到右下角，闭合曲线
        ctx.lineTo(endX, rectTopY);

        ctx.fill();

    }

}


